from datetime import datetime

from django.shortcuts import render
from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.generics import CreateAPIView, RetrieveAPIView, UpdateAPIView, GenericAPIView
from rest_framework.mixins import CreateModelMixin, UpdateModelMixin
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import GenericViewSet
from rest_framework_jwt.settings import api_settings
from rest_framework_jwt.views import ObtainJSONWebToken

from carts.utils import merge_cart_cookie_to_redis
from goods.models import SKU
from .models import User, Address
from .serializers import CreateUserSerializer, UserDetailSerializer, EmailSerializer, UserAddressSerializer, \
    AddressTitleSerializer, UserBrowserHistorySerializer, SKUSerializer
jwt_response_payload_handler = api_settings.JWT_RESPONSE_PAYLOAD_HANDLER


class UserView(CreateAPIView):
    """用户注册"""
    serializer_class = CreateUserSerializer


class UsernameCountView(APIView):
    """判断用户是否已注册"""

    def get(self, request, username):
        # 查询user表
        count = User.objects.filter(username=username).count()

        # 包装响应数据
        data = {
            "username": username,
            "count": count
        }
        return Response(data)


class MobileCountView(APIView):
    """判断手机号是否已注册"""

    def get(self, request, mobile):
        # 查询user表
        count = User.objects.filter(mobile=mobile).count()

        # 包装响应数据
        data = {
            "username": mobile,
            "count": count
        }
        return Response(data)


class UserDetailView(RetrieveAPIView):
    """用户相信信息"""
    serializer_class = UserDetailSerializer
    queryset = User.objects
    permission_classes = [IsAuthenticated, ]  # 只有通过认证的用户才能访问

    def get_object(self):
        """重写此方法返回 要展示的用户模型"""
        return self.request.user


class EmailView(UpdateAPIView):
    """更新用户邮箱"""
    serializer_class = EmailSerializer
    queryset = User.objects
    permission_classes = [IsAuthenticated, ]  # 只有通过认证的用户才能访问

    def get_object(self):
        """重写此方法返回 要展示的用户模型"""
        return self.request.user


class EmailVerifyView(APIView):

    def get(self, request):
        """激活用户邮箱"""
        # 获取前端传入的token
        token = request.query_params.get('token')
        if not token:
            return Response({"message": "非法请求"}, status=status.HTTP_400_BAD_REQUEST)
        # 把token解密并查询出对应的user
        user = User.check_verify_email_token(token)
        if not user:
            return Response({"message": "链接已失效请重新发送"}, status=status.HTTP_400_BAD_REQUEST)
        # 修改邮箱激活状态
        user.email_active = True
        user.save()
        return Response({"message": "ok"})


# class AddressViewSet(CreateModelMixin, GenericViewSet):
class AddressViewSet(UpdateModelMixin, GenericViewSet):
    """用户收货地址的增删改查"""

    permission_classes = [IsAuthenticated]
    serializer_class = UserAddressSerializer

    def get_queryset(self):
        return self.request.user.addresses.filter(is_deleted=False)

    def create(self, request, *args, **kwargs):
        user = request.user
        count = user.addresses.all().count()
        # count = Address.objects.filter(user=user).count()
        # 用户收货地址数量上线 最多只能有20个
        if count >= 20:
            return Response({'message': '收货地址数量上限'}, status=status.HTTP_400_BAD_REQUEST)

        # 创建序列化器进行反序列化
        serializer = self.get_serializer(data=request.data)
        # 调用序列化器的is_valid()
        serializer.is_valid(raise_exception=True)
        # 调用序列化器的save()
        # serializer.save(user_id=request.user.id)
        serializer.save()
        # 响应
        return Response(serializer.data, status=status.HTTP_201_CREATED)
        # return super().create(request, *args, **kwargs)

    def list(self, request, *args, **kwargs):
        """
        用户地址列表数据
        """
        queryset = self.get_queryset()
        serializer = self.get_serializer(instance=queryset, many=True)
        user = self.request.user
        return Response({
            'user_id': user.id,
            'default_address_id': user.default_address_id,
            'limit': 20,
            'addresses': serializer.data
        })

    @action(methods=['put'], detail=True)
    def status(self, request, *args, **kwargs):
        """
        修改默认地址
        """
        address = self.get_object()
        request.user.default_address = address
        request.user.save()
        return Response({'message': 'ok'}, status=status.HTTP_200_OK)

    # put /addresses/pk/title/
    # 需要请求体参数 title
    @action(methods=['put'], detail=True)
    def title(self, request, pk=None):
        """
        修改收货地址标题
        """
        address = self.get_object()
        serializer = AddressTitleSerializer(instance=address, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)


class UserBrowserHistoryView(CreateAPIView):
    """用户商品浏览记录"""
    serializer_class = UserBrowserHistorySerializer
    permission_classes = [IsAuthenticated]

    def get(self, request):
        redis_conn = get_redis_connection('history')

        sku_ids = redis_conn.lrange('history_%s' % request.user.id, 0, -1)
        sku_list = SKU.objects.filter(id__in=[i.decode() for i in sku_ids])  # 浏览记录的顺序会打乱

        serializer = SKUSerializer(instance=sku_list, many=True)

        return Response(serializer.data)


class UserAuthorizeView(ObtainJSONWebToken):
    """自定义账号密码登录视图,实现购物车合并"""

    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)

        if serializer.is_valid():
            user = serializer.object.get('user') or request.user
            token = serializer.object.get('token')
            response_data = jwt_response_payload_handler(token, user, request)
            response = Response(response_data)
            if api_settings.JWT_AUTH_COOKIE:
                expiration = (datetime.utcnow() +
                              api_settings.JWT_EXPIRATION_DELTA)
                response.set_cookie(api_settings.JWT_AUTH_COOKIE,
                                    token,
                                    expires=expiration,
                                    httponly=True)
            merge_cart_cookie_to_redis(request, user, response)
            return response

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
